/**
 * Created by Julia on 2016/05/28.
 */
define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'business/user/userConfig', 'appMessageBox', 'jquery-form/jquery-form.min', 'x-editable/x-editable.min'], function ($, domReady, appLocalStorage, appConst, global, userConfig, msgBox) {
    var components = {};
    var that;
    return {
        init: function () {
            that = this;
            components = {
                ta_description: $("#ta_description"),
                fm_password: $("#fm_password"),
                pwd_newPassword: "#pwd_newPassword"
            };
            that.initEditable();
            that.initEditableDescription();
            that.initPassword();
        },
        initEditableDescription: function() {
            components.ta_description.editable({
                url: 'user/update',
                rows: 10,
                params: function(params) {
                    var customParams = {};
                    customParams["id"] = params.pk;
                    customParams[params.name] = params.value;
                    return customParams;
                },
                success: function(response, newValue) {
                    if (response.code = 0) {
                        msgBox.errorBox(d.message != null ? d.message : 'GLOBAL_UPDATE_FAIL', 'MENU_SYSTEM_USER');
                        return false;
                    } else {
                        msgBox.successBox({
                            content: $.i18n.prop('GLOBAL_EDIT_SUCCESS')
                        });
                    }
                },
                error: function(response, newValue) {
                    //login timeout
                    if (response.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    //unable to connect to server
                    if (response.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    //find not page
                    if (response.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        initEditable: function() {
            $.fn.editable.defaults.mode = 'inline';
            $.fn.editable.defaults.url = 'user/update';
            $.fn.editableContainer.defaults.onblur = "submit";//Click Edit area outside the trigger to submit
            $.fn.editable.defaults.emptytext = "---";
            $.fn.editable.defaults.ajaxOptions = {
                error: function(xhr, textStatus, errorThrown) {
                    showOperationError(xhr, textStatus, errorThrown);
                }
            };

            $("a[data-type='text']").editable({
                params: function(params) {
                    var customParams = {};
                    customParams["id"] = params.pk;
                    customParams[params.name] = params.value;
                    return customParams;
                },
                validate: function(params) {
                    if ($(this).hasClass("name")) {
                        if ($.trim(params) == '') {
                            return $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('USER_NAME'));
                        }

                        if ($.trim(params).length > 32) {
                            return $.i18n.prop('VALIDATE_CHARACTER_SIZE_MAX',32);
                        }
                    }
                    if ($(this).hasClass("email")) {
                        if ($.trim(params) == '') {
                            return $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('USER_EMAIL'));
                        }
                        var re = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
                        if (!re.test($.trim(params))) {
                            return $.i18n.prop('VALIDATE_AVALID', $.i18n.prop('USER_EMAIL'));
                        }

                        if ($.trim(params).length > 64) {
                            return $.i18n.prop('VALIDATE_CHARACTER_SIZE_MAX', 64);
                        }
                    }
                },
                success: function(response, newValue) {
                    if (response.code = 0) {
                        if (d.message == "EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS") {
                            msgBox.errorBox(d.message, $("#loginName").val());
                        } else {
                            msgBox.errorBox(d.message != null ? d.message : 'GLOBAL_UPDATE_FAIL', 'MENU_SYSTEM_USER');
                        }
                        return false;
                    } else {
                        msgBox.successBox({
                            content: $.i18n.prop('GLOBAL_EDIT_SUCCESS')
                        });
                    }
                },
                error: function(response, newValue) {
                    //login timeout
                    if (response.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    //unable to connect to server
                    if (response.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    //find not page
                    if (response.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        initPassword: function(){
            components.fm_password.validate({
                // Rules for form validation
                rules: {
                    password: {
                        required: true,
                        minlength: 6,
                        maxlength: 32
                    },
                    newPassword: {
                        required: true,
                        minlength: 6,
                        maxlength: 32,
                        passwordCheck: true
                    },
                    repassword: {
                        required: true,
                        equalTo: components.pwd_newPassword
                    }
                },
                // Messages for form validation
                messages: {
                    password: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('USER_PASSWORD')),
                        minlength: $.i18n.prop('VALIDATE_CHARACTER_SIZE_MIN', 6),
                        maxlength: $.i18n.prop('VALIDATE_CHARACTER_SIZE_MAX', 32)
                    },
                    newPassword: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('USER_NEW_PASSWORD')),
                        minlength: $.i18n.prop('VALIDATE_CHARACTER_SIZE_MIN', 6),
                        maxlength: $.i18n.prop('VALIDATE_CHARACTER_SIZE_MAX', 32)
                    },
                    repassword: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('USER_REPASSWORD')),
                        equalTo:  $.i18n.prop('VALIDATE_PASSWORD_SAME')
                    }
                },
                // Ajax form submition
                submitHandler: function (form) {
                    $(form).ajaxSubmit({
                        success: function (d) {
                            if(d.code == 0) {
                                msgBox.errorBox(d.message != null ? d.message : 'GLOBAL_UPDATE_FAIL', 'MENU_SYSTEM_USER');
                            }else {
                                msgBox.successBox({
                                    content: $.i18n.prop('GLOBAL_EDIT_SUCCESS')
                                });
                                components.fm_password.hide();
                            }
                            components.fm_password[0].reset();
                            return false;
                        },
                        error: function(e){
                            if (e.status == 401) {
                                msgBox.sessionFailureBox();
                            }
                            if (e.status == 500) {
                                msgBox.serverFailureBox();
                            }
                            if (e.status == 404) {
                                msgBox.pathFailureBox();
                            }
                        }
                    });
                },
                // Do not change code below
                errorPlacement: function (error, element) {
                    error.insertAfter(element.parent());
                }
            });
        }
    };
});

